package com.legal.aid.app.service.impl;

import com.legal.aid.app.domain.dto.ChatDto;
import com.legal.aid.app.domain.dto.DeepSeekRequestBody;
import com.legal.aid.app.service.AiChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.http.HttpHeaders;
import org.springframework.web.reactive.function.BodyInserters;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

@Service
public class AiChatServiceImpl implements AiChatService {
    @Autowired
    @Qualifier("deepseekWebClient")
    private WebClient deepSeekTalkWebClient;

    @Override
    public String talk(String msg) {
        if (msg == null) {
            return "";
        }

        // 封装要发送给deepseek的消息列表
        List<DeepSeekRequestBody.Message> list = new ArrayList<>();
        DeepSeekRequestBody.Message message = new DeepSeekRequestBody.Message();
        message.setRole("user");
        message.setContent(msg);
        list.add(message);

        System.out.println("666");

        // 封装请求体
        DeepSeekRequestBody deepSeekRequestBody = new DeepSeekRequestBody();
        deepSeekRequestBody.setModel("deepseek-chat"); // 模型名称
        deepSeekRequestBody.setMessages(list); // 消息列表
        deepSeekRequestBody.setTemperature(0.7); // 控制输出的随机性
        deepSeekRequestBody.setMax_tokens(1024); // 控制输出的最大长度

        Mono<String> mono = deepSeekTalkWebClient.post()
                .uri("/chat/completions")
                .header(HttpHeaders.AUTHORIZATION, "Bearer sk-a8151c7e97f64d97b58b05d59a437ae5")
                .body(BodyInserters.fromObject(deepSeekRequestBody)) // 发送请求体
                .retrieve() // 响应处理器
                .bodyToMono(String.class); // 设置响应体 响应体是一个字符串

        // 同步获取响应体
        String result = mono.block();
        // 将响应体转换为json对象
        JSONObject jsonObject = JSONObject.parseObject(result);
        // 取出choices数组
        JSONArray choices = jsonObject.getJSONArray("choices");
        // 定义要返回的最后的结果
        String realresult = "";
        if (choices != null && choices.size() > 0) {
            // 取出第一个元素
            JSONObject mydata = choices.getJSONObject(0);
            // 取出第一个元素的message对象
            JSONObject message1 = mydata.getJSONObject("message");
            // 取出message对象的content属性
            realresult = message1.getString("content");
        } else {
            realresult = "抱歉，因为网络问题，无法获取到答案，请稍后再试！";
        }
        System.out.println(realresult);
        return realresult;
    }

}
